package com.zrc.japktool.ui;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.zrc.japktool.apk.merge.ApkMerge;
import com.zrc.japktool.apk.merge.AssetsConfig;
import com.zrc.japktool.apk.merge.manifest.ManifestXmlEditor;
import com.zrc.japktool.ui.view.RichTextFXLogView;
import com.zrc.japktool.ui.view.WebLogView;
import com.zrc.japktool.util.DialogUtil;
import com.zrc.japktool.util.FileUtil;
import com.zrc.japktool.util.TaskLog;
import javafx.application.Platform;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.input.Dragboard;
import javafx.scene.input.TransferMode;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class Tab6Controller_ApkMerge {

    private String jsonPath = null;
    private boolean isRunner = false;
    @FXML
    private VBox rootVBox;
    @FXML
    private RichTextFXLogView logView;
    @FXML
    private TextField gameApkPath_TextField;
    @FXML
    private TextField sdkApkPath_TextField;
    @FXML
    private TextField logoPic_TextField;
    @FXML
    private TextField package_TextField;
    @FXML
    private TextField softnum_TextField;
    @FXML
    private TextField appName_TextField;
    @FXML
    private TextField versionName_TextField;
    @FXML
    private TextField versionCode_TextField;
    @FXML
    private TextField appId_TextField;
    @FXML
    private TextField appKey_TextField;
    @FXML
    private TextField mediaId_TextField;
    @FXML
    private TextField secret_TextField;
    @FXML
    private ToggleGroup channelToggleGroup;
    @FXML
    private ToggleGroup companyToggleGroup;
    @FXML
    private ToggleGroup screenModeToggleGroup;

    private TaskLog log = new TaskLog() {

        @Override
        public void info(String msg) {logView.info(msg);}

        @Override
        public void warn(String msg) {logView.warn(msg);}

        @Override
        public void debug(String msg) {logView.debug(msg);}

        @Override
        public void error(String msg) {logView.error(msg);}

        @Override
        public void tip(String msg) {logView.tip(msg);}

    };

    @FXML
    public void initialize() {
        logView.tip("等待操作...");// 初始化日志区域
        setupDragAndDrop();// 设置拖放事件处理器
    }

    private void setupDragAndDrop() {
        rootVBox.setOnDragOver(event -> {
            Dragboard db = event.getDragboard();
            if (db.hasFiles()) {
                // 检查文件扩展名
                boolean hasValidFile = db.getFiles().stream().anyMatch(file -> file.getName().toLowerCase().endsWith(".json"));
                if (hasValidFile) {
                    event.acceptTransferModes(TransferMode.COPY);
                }
            }
            event.consume();
        });

        rootVBox.setOnDragDropped(event -> {
            Dragboard db = event.getDragboard();
            boolean success = false;
            if (db.hasFiles()) {
                List<File> files = db.getFiles();
                for (File file : files) {
                    String fileName = file.getName().toLowerCase();
                    String filePath = file.getAbsolutePath().replace("\\", "/");
                    if (fileName.endsWith(".json")) {
                        logView.tip("拖放配置文件: " + filePath);
                        importConfig(filePath);
                        success = true;
                        break;
                    }
                }
            }
            event.setDropCompleted(success);
            event.consume();
        });
    }

    private void importConfig(String jsonPath) {
        try {
            String jsonString = null;
            File file = new File(jsonPath);
            if (!file.exists()) {
                return;
            }
            BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            jsonString = sb.toString();
            reader.close();
            if (jsonString.isEmpty()) return;
            Gson gson = new Gson();
            AssetsConfig assetsConfig = gson.fromJson(jsonString, AssetsConfig.class);
            if (assetsConfig == null) return;
            package_TextField.setText(assetsConfig.getAppPackage());
            softnum_TextField.setText(assetsConfig.getAppSoftnum());
            appName_TextField.setText(assetsConfig.getAppName());
            versionName_TextField.setText(assetsConfig.getAppVersionName());
            versionCode_TextField.setText(assetsConfig.getAppVersionCode() + "");
            appId_TextField.setText(assetsConfig.getAppId());
            appKey_TextField.setText(assetsConfig.getAppKey());
            mediaId_TextField.setText(assetsConfig.getAppMediaid());
            secret_TextField.setText(assetsConfig.getAppSecret());

            String channel = assetsConfig.getChannel();
            for (Toggle toggle : channelToggleGroup.getToggles()) {
                RadioButton companyRadio = (RadioButton) toggle;
                String radioUserData = companyRadio.getUserData() == null ? "" : companyRadio.getUserData().toString();
                if (radioUserData.equals(String.valueOf(channel))) {
                    companyRadio.setSelected(true);
                    break;
                }
            }

            String targetCompany = assetsConfig.getAppSoftauthor();
            for (Toggle toggle : companyToggleGroup.getToggles()) {
                RadioButton companyRadio = (RadioButton) toggle;
                String radioUserData = companyRadio.getUserData() == null ? "" : companyRadio.getUserData().toString();
                if (radioUserData.isEmpty() && !radioUserData.contains("#")) continue;
                String curCompany = radioUserData.split("#")[0];
                String curCompanyNum = radioUserData.split("#")[1];
                if (targetCompany.equals(curCompany)) {
                    companyRadio.setSelected(true);
                    break;
                }
            }

            boolean isAppScreenmode = assetsConfig.isAppScreenmode();
            for (Toggle toggle : screenModeToggleGroup.getToggles()) {
                RadioButton companyRadio = (RadioButton) toggle;
                String radioUserData = companyRadio.getUserData() == null ? "true" : companyRadio.getUserData().toString();
                if (radioUserData.equals(String.valueOf(isAppScreenmode))) {
                    companyRadio.setSelected(true);
                    break;
                }
            }

        } catch (Exception e) {
            logView.error("错误: 导入配置发生异常 - " + e.getMessage());
        }
    }

    @FXML
    private void gameApkFileSelection() {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("选择游戏apk文件");
        FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("apk文件 (*.apk)", "*.apk");
        fileChooser.getExtensionFilters().add(extFilter);
        Stage stage = (Stage) rootVBox.getScene().getWindow();
        File selectedFile = fileChooser.showOpenDialog(stage);
        if (selectedFile != null) {
            String filePath = selectedFile.getAbsolutePath().replace("\\", "/");
            gameApkPath_TextField.setText(filePath);
            logView.tip("已选择游戏apk文件: " + filePath);
        } else {
            logView.tip("选择游戏apk文件已取消");
        }
    }

    @FXML
    private void sdkApkFileSelection() {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("选择SDK的apk文件");
        FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("apk文件 (*.apk)", "*.apk");
        fileChooser.getExtensionFilters().add(extFilter);
        Stage stage = (Stage) rootVBox.getScene().getWindow();
        File selectedFile = fileChooser.showOpenDialog(stage);
        if (selectedFile != null) {
            String filePath = selectedFile.getAbsolutePath().replace("\\", "/");
            sdkApkPath_TextField.setText(filePath);
            logView.tip("已选择SDK的apk文件: " + filePath);
        } else {
            logView.tip("选择SDK的apk文件已取消");
        }
    }

    @FXML
    private void logoPicFileSelection() {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("选择apk的logo图片");
        FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("apk文件 (*.png)", "*.png");
        fileChooser.getExtensionFilters().add(extFilter);
        Stage stage = (Stage) rootVBox.getScene().getWindow();
        File selectedFile = fileChooser.showOpenDialog(stage);
        if (selectedFile != null) {
            String filePath = selectedFile.getAbsolutePath().replace("\\", "/");
            logoPic_TextField.setText(filePath);
            logView.tip("已选择apk的logo图片: " + filePath);
        } else {
            logView.tip("选择apk的logo图片已取消");
        }
    }

    @FXML
    public void mergeApk(ActionEvent actionEvent) {

        if (isRunner) {
            DialogUtil.showInfoDialog((Stage)logView.getScene().getWindow(),"温馨提示！","当前任务正在进行: 请认真等待...");
            logView.error("当前任务正在进行: 请认真等待...");
            return;
        }

        String gameApkPath = gameApkPath_TextField.getText();
        if (gameApkPath.isEmpty()) {
            logView.error("错误: 请先选择游戏apk文件");
            return;
        }
        File gameApk = new File(gameApkPath);
        if (!gameApk.exists()) {
            logView.error("错误: 选择游戏apk文件不存在 - " + gameApkPath);
            return;
        }

        String sdkApkPath = sdkApkPath_TextField.getText();
        if (sdkApkPath.isEmpty()) {
            logView.error("错误: 请先选择SDK的apk文件");
            return;
        }
        File sdkApkFile = new File(sdkApkPath);
        if (!sdkApkFile.exists()) {
            logView.error("错误: 选择SDK的apk文件不存在 - " + sdkApkPath);
            return;
        }

        String picfilePath = logoPic_TextField.getText();
        if (picfilePath.isEmpty()) {
            logView.error("错误: 请先选择apk的logo图片");
            return;
        }
        File picFile = new File(picfilePath);
        if (!picFile.exists()) {
            logView.error("错误: 选择apk的logo图片不存在 - " + picfilePath);
            return;
        }

        AssetsConfig assetsConfig = new AssetsConfig();

        //入口
        try {
            ManifestXmlEditor gameManifestXmlEditor = new ManifestXmlEditor(gameApkPath);
            assetsConfig.setAppAct(gameManifestXmlEditor.getMainActivity());
        } catch (IOException e) {
            logView.error("你的游戏apk,解析失败...");
            return;
        }

        //渠道
        Toggle channelSelected = channelToggleGroup.getSelectedToggle();
        if (channelSelected != null) {
            RadioButton channelRadio = (RadioButton) channelSelected;
            String channel = channelRadio.getUserData() == null ? "oppo" : channelRadio.getUserData().toString();
            assetsConfig.setChannel(channel);
        }

        //公司
        Toggle companySelected = companyToggleGroup.getSelectedToggle();
        if (companySelected != null) {
            RadioButton companyRadio = (RadioButton) companySelected;
            String channelData = companyRadio.getUserData() == null ? "oppo" : companyRadio.getUserData().toString();
            if (channelData.isEmpty() && !channelData.contains("#")) return;
            String curCompany = channelData.split("#")[0];
            String curCompanyNum = channelData.split("#")[1];
            assetsConfig.setAppSoftauthor(curCompany);
            assetsConfig.setAppCompanyCode(Integer.valueOf(curCompanyNum));
        }

        // 屏幕
        Toggle screenModeSelected = screenModeToggleGroup.getSelectedToggle();
        if (screenModeSelected != null) {
            RadioButton screenModeRadio = (RadioButton) screenModeSelected;
            String screenMode = screenModeRadio.getUserData() == null ? "true" : screenModeRadio.getUserData().toString();
            assetsConfig.setAppScreenmode(screenMode.equals("true"));
        }

        //游戏包名
        if (package_TextField.getText().trim().isEmpty()) {
            logView.error("游戏包名不能为空...");
            return;
        }
        assetsConfig.setAppPackage(package_TextField.getText().trim());

        //软著
        if (softnum_TextField.getText().trim().isEmpty()) {
            logView.error("软著编号不能为空...");
            return;
        }
        assetsConfig.setAppSoftnum(softnum_TextField.getText().trim());

        //游戏名称
        if (appName_TextField.getText().trim().isEmpty()) {
            logView.error("游戏名称不能为空...");
            return;
        }
        assetsConfig.setAppName(appName_TextField.getText().trim());

        //版本名称
        if (versionName_TextField.getText().trim().isEmpty()) {
            logView.error("版本名称不能为空...");
            return;
        }
        assetsConfig.setAppVersionName(versionName_TextField.getText().trim());

        //版本名称
        if (versionCode_TextField.getText().trim().isEmpty()) {
            logView.error("版本名称不能为空...");
            return;
        }
        assetsConfig.setAppVersionCode(Integer.valueOf(versionCode_TextField.getText().trim()));

        //appId
        if (appId_TextField.getText().trim().isEmpty()) {
            logView.error("appId不能为空...");
            return;
        }
        assetsConfig.setAppId(appId_TextField.getText().trim());

        //appKey
        if (appKey_TextField.getText().trim().isEmpty()) {
            logView.error("appKey不能为空...");
            return;
        }
        assetsConfig.setAppKey(appKey_TextField.getText().trim());

        //mediaId
        if (mediaId_TextField.getText().trim().isEmpty()) {
            logView.error("mediaId不能为空...");
            return;
        }
        assetsConfig.setAppMediaid(mediaId_TextField.getText().trim());

        //secret
        if (secret_TextField.getText().trim().isEmpty()) {
            logView.error("secret不能为空...");
            return;
        }
        assetsConfig.setAppSecret(secret_TextField.getText().trim());

        assetsConfig.setAppDebug(false);
        assetsConfig.setAppUrl("https://aurora.jxrcgame.com/");
        //assetsConfig.setAppAct("com.fakerandroid.boot.FakerActivity");
        assetsConfig.setAppMode(0);

        List<AssetsConfig.ConfigBean> logConfigs = new ArrayList<>();
        logConfigs.add(new AssetsConfig.ConfigBean(1, -1, false, false, false, false, false));
        logConfigs.add(new AssetsConfig.ConfigBean(3, -1, false, false, false, false, false));
        logConfigs.add(new AssetsConfig.ConfigBean(4, -1, false, false, false, false, false));
        logConfigs.add(new AssetsConfig.ConfigBean(7, -1, false, false, false, false, false));
        logConfigs.add(new AssetsConfig.ConfigBean(8, -1, false, false, false, false, false));
        logConfigs.add(new AssetsConfig.ConfigBean(10, -1, false, false, false, false, false));
        assetsConfig.setConfig(logConfigs);


        // 创建一个Task来执行耗时操作
        Task<Void> task = new Task<>() {
            @Override
            protected Void call() {
                isRunner = true;
                logView.clear();
                logView.info("游戏合并...");
                try {
                    ApkMerge apkMerge = new ApkMerge(log);
                    apkMerge.apkMerge(gameApkPath, sdkApkPath, picfilePath, assetsConfig);
                    logView.info("游戏合并成功...");
                } catch (IOException e) {
                    logView.error("游戏合并失败...");
                }
                isRunner = false;
                return null;
            }
        };

        // 设置任务失败时的处理
        task.setOnFailed(event -> {
            isRunner = false;
            Throwable exception = task.getException();
            Platform.runLater(() -> {
                logView.error("游戏合并失败: " + exception.getMessage());
                exception.printStackTrace();
            });
        });

        // 启动后台线程执行任务
        new Thread(task).start();
    }

    public void exportJson(ActionEvent actionEvent) {
        String gameApkPath = gameApkPath_TextField.getText();
        if (gameApkPath.isEmpty()) {
            logView.error("错误: 请先选择游戏apk文件");
            return;
        }
        File gameApk = new File(gameApkPath);
        if (!gameApk.exists()) {
            logView.error("错误: 选择游戏apk文件不存在 - " + gameApkPath);
            return;
        }

        String sdkApkPath = sdkApkPath_TextField.getText();
        if (sdkApkPath.isEmpty()) {
            logView.error("错误: 请先选择SDK的apk文件");
            return;
        }
        File sdkApkFile = new File(sdkApkPath);
        if (!sdkApkFile.exists()) {
            logView.error("错误: 选择SDK的apk文件不存在 - " + sdkApkPath);
            return;
        }

        String picfilePath = logoPic_TextField.getText();
        if (picfilePath.isEmpty()) {
            logView.error("错误: 请先选择apk的logo图片");
            return;
        }
        File picFile = new File(picfilePath);
        if (!picFile.exists()) {
            logView.error("错误: 选择apk的logo图片不存在 - " + picfilePath);
            return;
        }

        AssetsConfig assetsConfig = new AssetsConfig();
        try {
            ManifestXmlEditor gameManifestXmlEditor = new ManifestXmlEditor(gameApkPath);
            assetsConfig.setAppAct(gameManifestXmlEditor.getMainActivity());
        } catch (IOException e) {
            logView.error("你的游戏apk,解析失败...");
            return;
        }

        //渠道
        Toggle channelSelected = channelToggleGroup.getSelectedToggle();
        if (channelSelected != null) {
            RadioButton channelRadio = (RadioButton) channelSelected;
            String channel = channelRadio.getUserData() == null ? "oppo" : channelRadio.getUserData().toString();
            assetsConfig.setChannel(channel);
        }

        //公司
        Toggle companySelected = companyToggleGroup.getSelectedToggle();
        if (companySelected != null) {
            RadioButton companyRadio = (RadioButton) companySelected;
            String channelData = companyRadio.getUserData() == null ? "oppo" : companyRadio.getUserData().toString();
            if (channelData.isEmpty() && !channelData.contains("#")) return;
            String curCompany = channelData.split("#")[0];
            String curCompanyNum = channelData.split("#")[1];
            assetsConfig.setAppSoftauthor(curCompany);
            assetsConfig.setAppCompanyCode(Integer.valueOf(curCompanyNum));
        }

        // 屏幕
        Toggle screenModeSelected = screenModeToggleGroup.getSelectedToggle();
        if (screenModeSelected != null) {
            RadioButton screenModeRadio = (RadioButton) screenModeSelected;
            String screenMode = screenModeRadio.getUserData() == null ? "true" : screenModeRadio.getUserData().toString();
            assetsConfig.setAppScreenmode(screenMode.equals("true"));
        }

        //游戏包名
        if (package_TextField.getText().trim().isEmpty()) {
            logView.error("游戏包名不能为空...");
            return;
        }
        assetsConfig.setAppPackage(package_TextField.getText().trim());

        //软著
        if (softnum_TextField.getText().trim().isEmpty()) {
            logView.error("软著编号不能为空...");
            return;
        }
        assetsConfig.setAppSoftnum(softnum_TextField.getText().trim());

        //游戏名称
        if (appName_TextField.getText().trim().isEmpty()) {
            logView.error("游戏名称不能为空...");
            return;
        }
        assetsConfig.setAppName(appName_TextField.getText().trim());

        //版本名称
        if (versionName_TextField.getText().trim().isEmpty()) {
            logView.error("版本名称不能为空...");
            return;
        }
        assetsConfig.setAppVersionName(versionName_TextField.getText().trim());

        //版本名称
        if (versionCode_TextField.getText().trim().isEmpty()) {
            logView.error("版本名称不能为空...");
            return;
        }
        assetsConfig.setAppVersionCode(Integer.valueOf(versionCode_TextField.getText().trim()));

        //appId
        if (appId_TextField.getText().trim().isEmpty()) {
            logView.error("appId不能为空...");
            return;
        }
        assetsConfig.setAppId(appId_TextField.getText().trim());

        //appKey
        if (appKey_TextField.getText().trim().isEmpty()) {
            logView.error("appKey不能为空...");
            return;
        }
        assetsConfig.setAppKey(appKey_TextField.getText().trim());

        //mediaId
        if (mediaId_TextField.getText().trim().isEmpty()) {
            logView.error("mediaId不能为空...");
            return;
        }
        assetsConfig.setAppMediaid(mediaId_TextField.getText().trim());

        //secret
        if (secret_TextField.getText().trim().isEmpty()) {
            logView.error("secret不能为空...");
            return;
        }
        assetsConfig.setAppSecret(secret_TextField.getText().trim());

        assetsConfig.setAppDebug(false);
        assetsConfig.setAppUrl("https://aurora.jxrcgame.com/");
        //assetsConfig.setAppAct("com.fakerandroid.boot.FakerActivity");
        assetsConfig.setAppMode(0);

        List<AssetsConfig.ConfigBean> logConfigs = new ArrayList<>();
        logConfigs.add(new AssetsConfig.ConfigBean(1, -1, false, false, false, false, false));
        logConfigs.add(new AssetsConfig.ConfigBean(3, -1, false, false, false, false, false));
        logConfigs.add(new AssetsConfig.ConfigBean(4, -1, false, false, false, false, false));
        logConfigs.add(new AssetsConfig.ConfigBean(7, -1, false, false, false, false, false));
        logConfigs.add(new AssetsConfig.ConfigBean(8, -1, false, false, false, false, false));
        logConfigs.add(new AssetsConfig.ConfigBean(10, -1, false, false, false, false, false));
        assetsConfig.setConfig(logConfigs);

        String saveJsonPath = null;
        if (jsonPath != null) {
            saveJsonPath = jsonPath;
        } else {
            saveJsonPath = new File(new File(gameApkPath).getParent(), assetsConfig.getAppPackage() + ".json").getAbsolutePath();
        }
        try {
            logView.info("准备导出的配置: " + assetsConfig);
            File jsonFile = new File(saveJsonPath);
            if (!jsonFile.getParentFile().exists()) { // 确保父目录存在
                jsonFile.getParentFile().mkdirs();
            }
            Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls().create();//格式化输出,序列化null值
            String jsonContent = gson.toJson(assetsConfig); // 调试用：检查JSON字符串
            logView.info("生成的JSON内容: " + jsonContent);

            try (BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(jsonFile), StandardCharsets.UTF_8))) {
                bufferedWriter.write(jsonContent); // 使用try-with-resources确保流自动关闭
            }

            logView.info("JSON配置导出成功: " + jsonFile.getAbsolutePath());
        } catch (Exception e) {
            logView.error("错误: 导出JSON文件失败 - " + e.getMessage());
            e.printStackTrace();
        }
    }

}